﻿using SD.Infrastructure.WPF.Models;
using SlamDunk.MES.IAppService.DTOs.Outputs.FoundationContext;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace SlamDunk.MES.Presentation.Maps
{
    /// <summary>
    /// 树形结构映射
    /// </summary>
    public static class TreeMap
    {
        #region # 工厂模型树节点映射 —— static Node ToNode(this FacilityInfo facility)
        /// <summary>
        /// 工厂模型树节点映射
        /// </summary>
        public static Node ToNode(this FacilityInfo facilityInfo)
        {
            return new Node(facilityInfo.Id, facilityInfo.Number, facilityInfo.Name, false, null);
        }
        #endregion

        #region # 工厂模型树映射 —— static ICollection<Node> ToTree(this IEnumerable<Facility...
        /// <summary>
        /// 工厂模型树映射
        /// </summary>
        public static ICollection<Node> ToTree(this IEnumerable<FacilityInfo> facilityInfos, Guid? parentNodeId)
        {
            //验证
            facilityInfos = facilityInfos == null ? new FacilityInfo[0] : facilityInfos.ToArray();

            //声明容器
            ICollection<Node> tree = new HashSet<Node>();

            //判断上级工厂模型Id是否为null
            if (!parentNodeId.HasValue)
            {
                //从根级开始遍历
                foreach (FacilityInfo facilit in facilityInfos.Where(x => x.IsRoot))
                {
                    Node node = facilit.ToNode();
                    tree.Add(node);

                    node.SubNodes = new ObservableCollection<Node>(facilityInfos.ToTree(node.Id));
                }
            }
            else
            {
                //从给定Id向下遍历
                foreach (FacilityInfo menu in facilityInfos.Where(x => x.ParentNodeId.HasValue && x.ParentNodeId.Value == parentNodeId.Value))
                {
                    Node node = menu.ToNode();
                    tree.Add(node);

                    node.SubNodes = new ObservableCollection<Node>(facilityInfos.ToTree(node.Id));
                }
            }

            return tree;
        }
        #endregion
    }
}
